# import string
import json, web, time, datetime
import abbrs
from abbrs import load_json

"""
with open('output.json', encoding='utf-8') as f:
    for i in reversed(json.load(f)):
        if isinstance(i, list) and len(i) == 4:
            print('---\n{}\n---\n{} iter {}, loss: {}'.format(i[0], i[1], i[2], i[3]))
"""

urls = (
	'/', 'index',
	'/(.*)', 'data_center',
)

app = web.application(urls, globals())

class data_center:
	def __init__(self):
		self.last_updated_at = -1

	def GET(self, name):
		"""
		with open('plot.js', encoding='utf-8') as f:
			class Template(string.Template):
				delimiter = '%'
			js = Template(f.read())
		"""
		
		# return js.substitute(data_here = self.plot_dat)
		
		if name == 'plot.js':
			return abbrs.read_file('plot.js')
		elif name == 'plot_data.json':
			self.get_data()
			train3 = [ 'train3', self.plot_dat, self.table ]
			dat = [ data_center.train1, data_center.train2, train3 ]
			
			web.header('Content-Type', 'application/json')
			return json.dumps(data_center.make_plot_series(*dat), indent='\t')
	
	def make_plot_series(*args):
		return [{
			'type:': 'area',
			'name': i[0],
			'data': i[1]
		} for i in args]
	
	def plot_data_translate(a):
		plot_dat = [ ]
		table = [ ]

		def time_translate(t):
			t = datetime.datetime.strptime(t, '%c') + datetime.timedelta(hours = 8)
			# return int(time.mktime(t)) * 1000 # JavaScript Data.UTC uses milliseconds
			return t.timestamp() * 1000
			# return 'Date.UTC({}, {}, {}, {}, {}, {})'.format(t[0], t[1], t[2], t[3], t[4], t[5])

		for i in a:
			if isinstance(i, list) and len(i) == 4:
				AXIS = 'ITER'
				if AXIS == 'TIME':
					time = time_translate(i[1])
					x = time
				elif AXIS == 'ITER':
					x = i[2]
					if 'Jan' in i[1]: x += 500000 # yedu
				else:
					print('What the fuck?')
					raise ValueError(AXIS)
				plot_dat.append([ x, i[3] ])
				table_format = '<tr><th>{}</th><td>{}</td><td>{}</td><td>{}</td></tr>'
				table.append(table_format.format(i[1], i[0], i[3], i[2]))			
		
		return plot_dat, table

	train1 = [ 'train1', *plot_data_translate(load_json('data/train1.json')) ]
	train2 = [ 'train2', *plot_data_translate(load_json('data/train2.json')) ]

	def get_data(self):
		if time.time() - self.last_updated_at < 60:
			return
		self.plot_dat, self.table = data_center.plot_data_translate(load_json('data/latest.json'))
		self.last_updated_at = time.time()
# todo: annotation
class index:
	def GET(self):
		template = web.template.frender('static/header-sidebar-template/header-sidebar-template.html')

		with open('plot.html', encoding='utf-8') as f:
			plot_html = f.read()

		return template({
			'title': 'Training Dashboard',
			'body': '<div id="container"></div>',
			'sidebar?': False,
			'scripts': plot_html
		})

"""
class see_static:
	def GET(self):
		raise web.seeother("/static/" + self.path)

class icon(see_static):
	path = "favicon.ico"

class template_css(see_static):
	path = "header-sidebar-template/header-sidebar-template.css"
"""

# web.config.debug = False

if __name__ == "__main__":
	app.run()